﻿using System;
using System.Windows;
using Microsoft.Practices.Unity;
using RG.Common;
using RG.Common.Configuration;
using RG.Common.Misc;
using RG.Common.WPF;
using RG.Common.WPF.Workplaces;
using log4net;

namespace RG.Client
{
    public partial class App
    {
        public const string AppName = "Realtor Guide";

        private IUnityContainer cfg;

        private void Application_Startup(object sender, StartupEventArgs e)
        {
#if !NO_CATCH
            ((App)sender).DispatcherUnhandledException += Application_DispatcherUnhandledException;
#endif
            log.Info(AppName + " started");
            try
            {
                var mw = new SingleFrameWorkplace { Title = AppName };

                cfg = new UnityContainer();
                cfg
                    .RegisterInstance(cfg)
                    //.BCStore_Frames()
                    .Common()
                    .Common_WPF()
                    .RegisterInstance<IWorkplace>(mw)
                    .RegisterType<IWorker, AsyncWorker>()


                    .RegisterInstance("FramesConfigFile", "Frames.xml")
                    .RegisterType<IUserSettings, RestrictedFileUserSettings>()

#if LOCAL
                    .RegisterInstance("ServicesPrefix", "Local")
#elif Release
                    .RegisterInstance("ServicesPrefix", "Release")
#else
.RegisterInstance("ServicesPrefix", "DEBUG")
#endif

;

                cfg.BuildUp(mw);

                var loginSettings = cfg.Resolve<IApplicationSettings>();
                mw.Title = string.Format("{0}", AppName);

                //mw.Show(login);

                mw.Show();
            }
            catch (Exception err)
            {
                log.TraceError(err, "StartUp");
                MessageBox.Show(err.Message);
            }
        }

        private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            log.TraceError(e.Exception, "Application_DispatcherUnhandledException");

            var result = MessageBox.Show("Неустранимая ошибка:\n\n" + e.Exception.Message + "\n\n" +
                                         "Вы можете попытаться продолжить работу, но корректная работа программы не гарантируется. \n\n" +
                                         "Продолжить работу ?", AppName, MessageBoxButton.YesNo, MessageBoxImage.Error);

            e.Handled = (result == MessageBoxResult.Yes);
            if (!e.Handled) Shutdown(-1);
        }

        private static readonly ILog log = LogManager.GetLogger(
            System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    }
}